<template>
    <div class="container">
        <div class="top-title">视频转码</div>
        <div class="top-main"> 
            <div class="top-tip">
                <span> *课时视频文件在此处上传，格式为MP4,视频文件不超过500M,若大于500M请转码后分割课时视频内容 ，视频上传前会进行上传校验,</span>
                <span style="color: #ff9f6b;"> 不符合标准请转码后重试！</span>
            </div>
            <!-- 上传视频 -->
            <div class="form" v-if="active === 0">
                <el-form :model="form" label-width="auto" style="max-width: 600px">
                    <el-form-item label="上传端口">
                        <el-radio-group v-model="form.uploadport">
                            <el-radio value="jdy" border>简道云</el-radio>
                            <el-radio value="txy" border>腾讯云</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label="课时标签">
                        <el-input required v-model="form.courseTag" placeholder="请输入课时标签：与上传的视频课程一致，例：省考笔试分校行测模考试卷讲解" />
                    </el-form-item>
                    <el-form-item label="视频上传">
                        <div class="upload-button">
                            <div class="upload">
                                <el-upload class="upload-demo" drag multiple  action="#"
                                    :auto-upload="false" :before-upload="beforeUpload" :on-change="handleVideoChange"
                                    :on-remove="removeList">
                                    <i class="el-icon-upload"></i>
                                    <div class="el-upload__text">将文件拖到此处，或<em class="el-upload--text">点击上传</em></div>
                                    <div class="el-upload__tip" slot="tip">仅支持视频文件</div>
                                </el-upload>
                            </div>
                            <div class="upload-progress">
                                <!-- <div class="left-progress">
                                    <el-progress :percentage="50" type="circle" />
                                </div> -->
                                <div class="upload-button">
                                    <el-button type="primary" @click="uploadVideo">上传</el-button>
                                    <el-button type="info">取消</el-button>
                                </div>
                            </div>
                        </div>
                    </el-form-item>
                    <el-form-item label="视频检验">
                        <el-table :data="tableData" style="width: 100%">
                            <el-table-column type="expand">
                                <template #default="props">
                                    <el-table :data="props.row.data" :border="true">
                                        <el-table-column prop="name" label="名称" />
                                        <el-table-column prop="parameter" label="参数" />
                                        <el-table-column prop="standard" label="标准" />
                                        <el-table-column prop="suite" label="是否满足">
                                            <template #default="props">
                                                <div v-if="props.row.suite === '满足'">
                                                    <el-tag type="success"> {{ props.row.suite }}</el-tag>
                                                </div>
                                                <div v-else>
                                                    <el-tag type="danger"> {{ props.row.suite }}</el-tag>
                                                </div>
                                            </template>
                                        </el-table-column>
                                    </el-table>
                                </template>
                            </el-table-column>
                            <el-table-column label="文件名" prop="fileName" />
                            <el-table-column label="是否符合要求" prop="requirement" />
                        </el-table>
                    </el-form-item>
                </el-form>
            </div>
            <!-- 上传讲义 -->
            <div class="upload-pdf" v-if="active === 1">
                <el-table :data="tableData" style="width: 100%">
                    <el-table-column prop="date" label="课时名称" width="180" />
                    <el-table-column prop="name" label="" width="180" />
                    <el-table-column prop="address" label="Address" />
                </el-table>
            </div>
        </div>
        <el-dialog v-model="dialogTableVisible" title="上传视频" :close-on-click-modal="false"
            :close-on-press-escape="false" :show-close="false" width="80%">
            <div class="progress">
                <div>
                    <el-button type="danger" @click="deleteAll" v-if="idList.length > 0">批量删除</el-button>
                </div>
                <el-table :data="uploadList" style="width: 100%" @selection-change="handleSelectionChange">
                    <el-table-column type="selection" width="55" />
                    <el-table-column prop="fileName" label="课时名称" width="180" />
                    <el-table-column label="上传进度(视频)">
                        <template #default="scope">
                            <el-progress :percentage="scope.row.progressPercent" />
                        </template>
                    </el-table-column>
                    <el-table-column label="上传进度(讲义)">
                        <template #default="scope">
                            <div v-if="!scope.row.pdfStatus">
                                <el-upload ref="uploadRef" class="upload-demo" action="#"
                                    :http-request="(file) => uploadRquest(file, scope.row)">
                                    <template #trigger>
                                        <el-button type="primary" :disabled="!scope.row.status">上传讲义</el-button>
                                    </template>
                                </el-upload>
                            </div>
                            <div v-else="scope.row.pdfStatus">
                                <el-progress :percentage="scope.row.progressPercentPdf" />
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column label="选择讲师(必选)">
                        <template #default="scope">
                            <el-select v-model="scope.row.info" placeholder="请选择讲师" size="large"
                                @change="changeValue($event, scope.row)" :disabled="!scope.row.status">
                                <el-option v-for="item, index in options" :key="index" :label="item.name"
                                    :value="item._id" />
                            </el-select>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作">
                        <template #default="scope">
                            <el-button type="danger" :disabled="!scope.row.status"
                                @click="deleteOne(scope.row.class_number)">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
            <template #footer>
                <div class="dialog-footer">
                    <el-popconfirm title="请确保当前所有视频已经绑定讲师信息？" confirm-button-text="确认" cancel-button-text="取消" @confirm="confirm">
                        <template #reference>
                            <el-button>确定</el-button>
                        </template>
                    </el-popconfirm>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref } from 'vue'
import { reactive } from 'vue'
import { ElMessage } from 'element-plus'
import request from '../../utils/http/request';
import { sumbitLesson, uploadFdf, searchTeacher } from '../../api/uploadVideo'
import { uploadFileList, deleteCourse, deleteCourseList, getSyncStatus } from '../../api/uploadVideoList'
import {timeStringToSeconds} from '../../utils/date'
import { ElLoading } from 'element-plus'
import { useRouter } from 'vue-router';
const router = useRouter();
// import type { MediaInfo, ReadChunkFunc } from 'mediainfo.js'
const dialogTableVisible = ref(false)
const active = ref(0)
const form = reactive({
    uploadport: 'jdy',//上传端口
    courseTag: '',//课时标签
    date1: '',
    date2: '',
    delivery: false,
    type: [],
    resource: '',
    desc: '',
})
const options = ref([])

const getTeacherList = () => {
    searchTeacher({ name: '', phone: '' }).then(res => {
        if (res) {
            options.value = res.list
            console.log(options, 'options');
        }
    })
}
getTeacherList()
const tableData = ref([]);


const beforeUpload = (file) => { 
    const isVideo = file.type.startsWith('video/');
    const isLt500M = file.size / 1024 / 1024 < 500;
    if (!isVideo) {
        ElMessage.error('只能上传视频文件!');
        return false;
    }
    if (!isLt500M) {
        ElMessage.error('视频大小超过500MB，超出限制!');
        return false;
    }
    return true;
};

let files = [];
const handleVideoChange = async (file, fileList) => {
    console.log(file, 'file');
    console.log(tableData.value, 'tableData')
    files.push(file); 
    const result = await checkMediaFile(file.raw);
    updateTableData(result, file.name, file.uid, file);
};

const updateTableData = (result, fileName, uid, file) => { 
    const tracks = result.media.track;
    const videoTrack = tracks[0];
    const audioTrack = tracks[2];
    const data = [
        { name: '视频大小', parameter: (videoTrack.DataSize / 1024 / 1024).toFixed(2) + 'M', standard: '500M', suite: videoTrack.DataSize < 500 * 1024 * 1024 ? '满足' : '不满足' },
        { name: '时长', parameter: `${Math.floor(videoTrack.Duration / 60)}:${Math.floor(videoTrack.Duration % 60) < 10 ? '0' + Math.floor(videoTrack.Duration % 60) : Math.floor(videoTrack.Duration % 60)}`, standard: '60:00', suite: videoTrack.Duration < 3600 ? '满足' : '不满足' },
        { name: '屏幕分辨率', parameter: `${tracks[1].Sampled_Width}×${tracks[1].Sampled_Height}`, standard: '1280×720', suite: `${tracks[1].Sampled_Width}×${tracks[1].Sampled_Height}` === '1280×720' || `${tracks[1].Sampled_Width}×${tracks[1].Sampled_Height}` === '1920×1080' ? '满足' : '不满足' },
        { name: '视频格式', parameter: videoTrack.Format, standard: 'MPEG-4', suite: videoTrack.Format === 'MPEG-4' ? '满足' : '不满足' },
        { name: '编解码器', parameter: `${tracks[1].Format}(${tracks[1].Encoded_Library_Name})`, standard: 'AVC(x264)', suite: (`${tracks[1].Format}(${tracks[1].Encoded_Library_Name})`).indexOf("AVC")!==-1 ? '满足' : '不满足' },
        { name: '视频码率', parameter: (tracks[1].BitRate / 1000), standard: '600 kb/s - 800 kb/s', suite: tracks[1].BitRate < 800 * 1000 ? '满足' : '不满足' },
        { name: '帧率', parameter: tracks[1].FrameRate, standard: '23.976 / 24 / 25', suite: [23.976, 24, 25].includes(tracks[1].FrameRate) ? '满足' : '不满足' },
        { name: '音频格式', parameter: audioTrack.Format, standard: 'AAC', suite: audioTrack.Format === 'AAC' ? '满足' : '不满足' },
        { name: '音频码率', parameter: (audioTrack.BitRate / 1000), standard: '<150 kb/s', suite: audioTrack.BitRate < 150 * 1000 ? '满足' : '不满足' },
    ]; 
    if (form.uploadport   === 'txy') {
        data[0] =  { name: '视频大小', parameter: (videoTrack.DataSize / 1024 / 1024).toFixed(2) + 'M', standard: '1000M', suite: videoTrack.DataSize < 1000 * 1024 * 1024 ? '满足' : '不满足' }
        data[1] = { name: '时长', parameter: `${Math.floor(videoTrack.Duration / 60)}:${Math.floor(videoTrack.Duration % 60) < 10 ? '0' + Math.floor(videoTrack.Duration % 60) : Math.floor(videoTrack.Duration % 60)}`, standard: '90:00', suite: videoTrack.Duration < 5400 ? '满足' : '不满足' }
    }
    const requirement = data.every(item => item.suite === '满足') ? '符合' : '不符合';  
    tableData.value.push({ fileName, data, requirement, uid, file });
};


const checkMediaFile = (file) => {
    return new Promise((resolve, reject) => {
        const getSize = () => file.size;
        const readChunk = (chunkSize, offset) => {
            return new Promise((resolve, reject) => {
                const reader = new FileReader();
                reader.onload = (event) => {
                    if (event.target.error) {
                        reject(event.target.error);
                    }
                    resolve(new Uint8Array(event.target.result));
                };
                reader.readAsArrayBuffer(file.slice(offset, offset + chunkSize));
            });
        };
        window.MediaInfo.mediaInfoFactory
            ()
            .then((media) => {
                media
                    .analyzeData(getSize, readChunk)
                    .then((result) => {
                        resolve(result);
                    })
                    .catch((error) => {
                        reject(error);
                    });
            })
            .catch((error) => {
                reject(error);
            });
    });
};
const uploadVideo = () => { 
    if (tableData.length === 0) {
        ElMessage.error('请选择文件')
        return
    }
    if (form.courseTag.length === 0) {
        return ElMessage.error('请填写课程标识')
    }
    const iConfon  =  tableData.value.every((item) => item.requirement === '符合')
    if (!iConfon) {
        return ElMessage.error('视频不符合要求')
    }
    dialogTableVisible.value = true
    for (let i = 0; i < tableData.value.length; i++) {
        uploadList.value.push({
            fileName: tableData.value[i].fileName.split('.mp4')[0],
            progressPercent: 0,
            files: tableData.value[i].file,
            progressPercentPdf: 0,
            uid: tableData.value[i].uid,
            status: false,
            pdfStatus: false,
            class_number: '',
            info: "",
            class_name: '',
            class_time:timeStringToSeconds(tableData.value[i].data[1].parameter),
        })
    }
    //循环发送请求
    const promises = []
    for (let i = 0; i < uploadList.value.length; i++) {
        let promise = uploadItem(uploadList.value[i])
        promises.push(promise)
    }
    //等待所有请求都完成
    Promise.allSettled(promises).then((res) => {
        uploadList.value = uploadList.value.map((item) => {
            item.status = true
            return item
        })
        console.log(tableData.value, 'tableData')
        res.forEach(async (course) => {
            console.log(course, 'course')
            if (course.status === 'fulfilled') {
                console.log(form)
                console.log(course.value.data, '数据')
                if (form.uploadport
                    === 'txy') {
                    let data = await getSyncStatus(course.value.data)
                    if (data.code === '200') {
                        const uid = uploadList.value.findIndex((item) => item.uid == data.data[0].uuid
                        )
                        uploadList.value[uid].class_number = data.data[0].class_number
                        uploadList.value[uid].class_name =data.data[0].class_name
                    }
                }
                if (form.uploadport
                    === 'jdy') {
                    const uid = uploadList.value.findIndex((item) => item.uid == course.value.data[0].uuid
                    )
                    uploadList.value[uid].class_number = course.data[0].class_number
                    uploadList.value[uid].class_name = course.data[0].class_name
                }
            } else {
                ElMessage.error('上传失败')
            }
        })
    }).catch((err) => {
        console.log(err, 'err')
    })

}
const uploadItem = (file) => {
    let data = localStorage.getItem('token')
    let { teacher_name, phone } = JSON.parse(data)
    let formInfo = new FormData()
    formInfo.append('video', file.files.raw)
    formInfo.append('port', form.uploadport)
    formInfo.append('updateUserName', teacher_name)
    formInfo.append('updateUsserPhone', phone)
    formInfo.append("class_names", file.files.name.split('.mp4')[0])
    formInfo.append('identity', form.courseTag)
    formInfo.append('uuid', file.uid)
    return new Promise((resolve, reject) => {
        request({
            url: "/lesson/batchInsert",
            method: "POST",
            data: formInfo,
            headers: {
                ' Content-Type': 'multipart/form-data'
            },
            timeout: 100000000,
            onUploadProgress: (progressEvent) => {
                file.progressPercent = Number(
                    ((progressEvent.loaded / progressEvent.total) * 100).toFixed(0)
                )
                //   上传进度和对勾显示时间不相符,让进度条卡到98,等后台返回结果在显示100
                if (file.progressPercent >= 98) {
                    file.progressPercent = 98
                }
            }
        }).then(res => {
            if (res.code === '200') {
                file.progressPercent = 100
                resolve(res)
            } else {
                file.progressPercent = 0
                reject(res)
            }
        }).catch(error => {
            reject(error)
            console.log(error, 'error')
        })
    })
}
// 上传进度
const uploadList = ref([])
/**
 * 从上传列表中移除指定文件
 *
 * @param {File} file 要移除的文件对象
 */
const removeList = (file) => {
    const uid = file.uid
    tableData.value = tableData.value.filter((item) => item.uid !== uid);
}
/**
 * 上传讲义
 *
 * @param file 上传的文件对象
 * @param item 上传的文件项对象
 */
const uploadRquest = (file, item) => {
    console.log(file, 'file')
    console.log(item, 'item')
    let form = new FormData()
    form.append('file', file.file)
    form.append('class_number', item.class_number)
    item.pdfStatus = true;
    request({
        url: "/lesson/uploadFile",
        method: "post",
        data: form,
        onUploadProgress: (progressEvent) => {
            item.progressPercentPdf = Number(
                ((progressEvent.loaded / progressEvent.total) * 100).toFixed(0)
            )
            //   上传进度和对勾显示时间不相符,让进度条卡到98,等后台返回结果在显示100
            if (item.progressPercentPdf >= 98) {
                item.progressPercentPdf = 98
            }
        }
    }).then(res => {
        if (res.code === '200') {
            item.progressPercentPdf = 100
        } else {
            item.progressPercentPdf = 0
        }
    }).catch(err => {
        console.log(err, 'err')
    })
}
//下拉选项值
const changeValue = (id, item) => {
    const chooseItem = options.value.filter((item) => item._id == id)
    const { class_number, class_time, class_name } = item
    const { name, phone, picture } = chooseItem[0]
    let params = {
        class_number,
        class_teacher: name,
        class_time,
        teacher_phone: phone,
        picture: picture[0].url,
        class_name
    }
//     const loading = ElLoading.service({
//     lock: true,
//     text: 'Loading',
//     background: 'rgba(0, 0, 0, 0.7)',
//   })
    sumbitLesson(params).then((res) => {
        // loading.close()
        if (res) {
            console.log('修改成功')
        }
    }).catch((err) => {
        // loading.close()
    })
}
/**
 * 删除指定课程
 *
 * @param id 课程编号
 */
const deleteOne = (id) => {
    let data = localStorage.getItem('token')
    let { teacher_name, phone } = JSON.parse(data)
    let params = {
        class_number: id,
        updateUserName: teacher_name,
        updateUsserPhone: phone
    }

    deleteCourse(params).then(res => {
        if (res.code === '200') {
            uploadList.value = uploadList.value.filter(item => item.class_number !== id)
            ElMessage.success('删除成功')
        }
    })
}
const idList = ref([])
const handleSelectionChange = (val) => {
    console.log(val, 'val')
    idList.value = val.map(item => item.class_number)
}
/**
 * 删除所有选定的课时
 */
const deleteAll = () => {
    if (idList.value.length === 0) {
        ElMessage.error('请选择课时')
        return
    }
    let data = localStorage.getItem('token')
    let { teacher_name, phone } = JSON.parse(data)
    let params = {
        ids: idList.value.map(item => item.class_number).join(','),
        updateUserName: teacher_name,
        updateUsserPhone: phone
    }
    console.log(params)
    deleteCourseList(params).then(res => {
        if (res.code === '200') {
            uploadList.value = uploadList.value.filter(item => !idList.value.includes(item.class_number))
            ElMessage.success('删除成功')
        }
    })
}
const confirm = () => {
    ElMessage.success('课时上传成功！')
    dialogTableVisible.value = false
    tableData.value = []
    uploadList.value = []
    setTimeout(() => {
        router.push({ path: "/course" });    
    }, 1000); 
}
</script>

<style scoped>
.top-title {
    height: 100px;
    line-height: 100px;
    background-color: #ffffff;
    padding-left: 20px;
}

.top-main {
    box-sizing: border-box;
    margin: 20px;
    min-height: calc(100vh - 140px);
    background-color: #ffffff;
    padding: 20px;
    box-sizing: border-box
}

.top-tip {
    margin-top: 20px;
    font-size: 14px;
    color: #606266;
}

.form {
    margin-top: 20px;
}

.upload-progress {
    display: flex;
    align-items: center;
}

.left-progress {
    margin-right: 10px;
}

.progress {
    padding: 50px 0;
}
</style>